/*
 *    Copyright 2010-2013 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package com.google.code.jbauble.db;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.sql.DataSource;

import com.google.code.jbauble.db.exception.DataAccessException;
import com.google.code.jbauble.db.mysql.MysqlDatastore;
import com.google.code.jbauble.db.mysql.MysqlNative;

public class DatastoreManager {
	public static String DEFAULT_DATASTORE = "default";
	private static Datastore defaultDatastore;
	private static Map<String, Datastore> datastores = new HashMap<String, Datastore>();
	
	public static Datastore getDefaultDatastore() {
		return defaultDatastore;
	}
	
	public static Datastore getDatastore(String name) {
		if (name != null && name.equals(DEFAULT_DATASTORE)) {
			return defaultDatastore;
		}
		else {
			return datastores.get(name);
		}
	}
	
	public static void addDatastore(String name, Datastore ds) {
		if (name != null && name.equals(DEFAULT_DATASTORE)) {
			defaultDatastore = ds;
		}
		else {
			datastores.put(name, ds);
		}
	}
	
	public static String DB_TYPE = "db.type";
	public static String DB_DBNAME = "db.dbName";
	public static String DB_USER = "db.user";
	public static String DB_PWD = "db.pwd";
	public static String DB_MINPOOL = "db.minPool";
	public static String DB_MAXPOOL = "db.maxPool";
	public static String DB_PARTITION = "db.partition";
	public static String DB_PACKAGES = "db.packages";
	
	public static void initDatabase(DataSource datasource, String env, Properties p) throws DataAccessException {
		if (p.getProperty(DB_TYPE) == null 
				|| p.getProperty(DB_PACKAGES) == null 
				|| p.getProperty(DB_PACKAGES).equals(""))
			return;
		//String url = p.getProperty("db." + env + ".url");
		Datastore ds = new MysqlDatastore(datasource,
				getPackages(p));
		
		addDatastore(DEFAULT_DATASTORE, ds);
	}

	private static String[] getPackages(Properties p) {
		String ps = p.getProperty(DB_PACKAGES);
		if (ps == null || ps.equals(""))
			return null;
		
		return ps.split(",");
	}
}
